package org.csu.onlineedubackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.csu.onlineedubackend.entity.Course;
import org.csu.onlineedubackend.entity.CourseSubscribe;
import org.csu.onlineedubackend.mapper.CourseMapper;
import org.csu.onlineedubackend.mapper.CourseSubscribeMapper;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.StudentCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.csu.onlineedubackend.service.LogService;
import org.csu.onlineedubackend.service.UserService;
import org.csu.onlineedubackend.entity.User;
import jakarta.servlet.http.HttpServletRequest;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程订阅控制器
 */
@RestController
@Slf4j
@RequestMapping("/api/courses")
public class CourseSubscribeController {
    
    @Autowired
    private CourseSubscribeMapper courseSubscribeMapper;
    
    @Autowired
    private StudentCourseService studentCourseService;
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private LogService logService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 查询课程订阅状态
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @return 订阅状态
     */
    @GetMapping("/{courseId}/subscribe")
    public CommonResponse<Boolean> isSubscribed(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId) {
        log.info("查询课程订阅状态 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 参数校验
            if (courseId == null || studentId == null) {
                log.error("查询课程订阅状态失败 - 参数为空, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数不能为空");
            }
            
            // 查询订阅状态
            QueryWrapper<CourseSubscribe> wrapper = new QueryWrapper<>();
            wrapper.eq("course_id", courseId).eq("student_id", studentId);
            Long count = courseSubscribeMapper.selectCount(wrapper);
            
            boolean isSubscribed = count != null && count > 0;
            log.info("查询课程订阅状态结果 - 课程ID: {}, 学生ID: {}, 是否已订阅: {}", 
                    courseId, studentId, isSubscribed);
            
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), 
                    isSubscribed ? "已订阅" : "未订阅", isSubscribed);
        } catch (Exception e) {
            log.error("查询课程订阅状态异常 - 课程ID: {}, 学生ID: {}, 错误: {}", 
                    courseId, studentId, e.getMessage(), e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "查询订阅状态异常");
        }
    }
    
    /**
     * 查询课程订阅状态和订阅人数
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @return 订阅状态和订阅人数
     */
    @GetMapping("/{courseId}/subscription/status")
    public CommonResponse<Map<String, Object>> getSubscriptionStatus(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId) {
        log.info("查询课程订阅状态和订阅人数 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 参数校验
            if (courseId == null || studentId == null) {
                log.error("查询课程订阅状态和订阅人数失败 - 参数为空, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数不能为空");
            }
            
            Map<String, Object> result = new HashMap<>();
            
            // 查询订阅状态
            QueryWrapper<CourseSubscribe> wrapper = new QueryWrapper<>();
            wrapper.eq("course_id", courseId).eq("student_id", studentId);
            Long count = courseSubscribeMapper.selectCount(wrapper);
            
            boolean isSubscribed = count != null && count > 0;
            log.info("查询课程订阅状态结果 - 课程ID: {}, 学生ID: {}, 是否已订阅: {}", 
                    courseId, studentId, isSubscribed);
            
            // 获取课程信息和订阅人数
            Course course = courseMapper.selectById(courseId);
            int subscriptionCount = 0;
            
            if (course != null && course.getSubscriberCount() != null) {
                subscriptionCount = course.getSubscriberCount();
            } else {
                // 如果课程表中没有订阅人数，直接从订阅表中计算
                try {
                    String sql = "SELECT COUNT(*) FROM course_subscribe WHERE course_id = ?";
                    Integer subCount = jdbcTemplate.queryForObject(sql, Integer.class, courseId);
                    if (subCount != null) {
                        subscriptionCount = subCount;
                    }
                } catch (Exception e) {
                    log.error("统计订阅人数异常 - 课程ID: {}, 错误: {}", courseId, e.getMessage());
                }
            }
            
            result.put("subscribed", isSubscribed);
            result.put("subscriptionCount", subscriptionCount);
            
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", result);
        } catch (Exception e) {
            log.error("查询课程订阅状态和订阅人数异常 - 课程ID: {}, 学生ID: {}, 错误: {}", 
                    courseId, studentId, e.getMessage(), e);
            
            // 即使出现异常，也返回一个有效的结果
            Map<String, Object> fallbackResult = new HashMap<>();
            fallbackResult.put("subscribed", false);
            fallbackResult.put("subscriptionCount", 0);
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询异常，返回默认值", fallbackResult);
        }
    }
    
    /**
     * 添加课程订阅
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @return 操作结果
     */
    @PostMapping("/{courseId}/subscribe")
    public CommonResponse<Boolean> subscribe(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId,
            HttpServletRequest request) {
        log.info("添加课程订阅 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 硬编码SQL语句直接插入
            try {
                // 1. 首先检查是否已订阅
                String checkSql = "SELECT COUNT(*) FROM course_subscribe WHERE course_id = " + courseId + " AND student_id = " + studentId;
                log.info("执行SQL: {}", checkSql);
                
                Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class);
                log.info("查询结果: {}", count);
                
                if (count != null && count > 0) {
                    log.info("课程已订阅 - 课程ID: {}, 学生ID: {}", courseId, studentId);
                    return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "已订阅", true);
                }
                
                // 2. 执行插入
                String insertSql = "INSERT INTO course_subscribe (course_id, student_id) VALUES (" + courseId + ", " + studentId + ")";
                log.info("执行SQL: {}", insertSql);
                
                int result = jdbcTemplate.update(insertSql);
                log.info("插入结果: {}", result);

                if (result > 0) {
                    // 日志记录
                    User user = userService.getById(studentId);
                    String username = user != null ? user.getUsername() : null;
                    String ip = request.getRemoteAddr();
                    String userAgent = request.getHeader("User-Agent");
                    Course course = courseMapper.selectById(courseId);
                    String courseTitle = course != null ? course.getTitle() : null;
//                    System.out.println(2222);
                    logService.recordCourseSubscribe(studentId, username, courseId, courseTitle, ip, userAgent, true);
                    return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "订阅成功", true);
                } else {
                    return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "订阅失败: 数据库插入失败");
                }
            } catch (Exception e) {
                log.error("SQL操作异常: {}", e.getMessage(), e);
                e.printStackTrace();
                
                // 尝试使用最原始的JDBC方式
                try {
                    // 获取原始连接
                    java.sql.Connection conn = jdbcTemplate.getDataSource().getConnection();
                    log.info("获取数据库连接成功");
                    
                    // 使用原始Statement
                    java.sql.Statement stmt = conn.createStatement();
                    log.info("创建Statement成功");
                    
                    // 执行插入
                    String rawSql = "INSERT INTO course_subscribe (course_id, student_id) VALUES (" + courseId + ", " + studentId + ")";
                    log.info("执行原始SQL: {}", rawSql);
                    
                    int rawResult = stmt.executeUpdate(rawSql);
                    log.info("原始SQL执行结果: {}", rawResult);
                    
                    // 关闭资源
                    stmt.close();
                    conn.close();
//                    System.out.println(33333333);
                    if (rawResult > 0) {
//                        System.out.println(444444444);
                        // 日志记录
                        User user = userService.getById(studentId);
                        String username = user != null ? user.getUsername() : null;
                        String ip = request.getRemoteAddr();
                        String userAgent = request.getHeader("User-Agent");
                        Course course = courseMapper.selectById(courseId);
                        String courseTitle = course != null ? course.getTitle() : null;
                        logService.recordCourseSubscribe(studentId, username, courseId, courseTitle, ip, userAgent, true);
                        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "订阅成功(原始JDBC)", true);
                    } else {
                        return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "订阅失败: 原始JDBC插入失败");
                    }
                } catch (Exception ex) {
                    log.error("原始JDBC操作异常: {}", ex.getMessage(), ex);
                    ex.printStackTrace();
                    return CommonResponse.createForError(ResponseCode.ERROR.getCode(), 
                            "订阅失败: " + e.getMessage() + "; 原始JDBC异常: " + ex.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("添加课程订阅总异常: {}", e.getMessage(), e);
            e.printStackTrace();
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "订阅异常: " + e.getMessage());
        }
    }
    
    /**
     * 取消课程订阅
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @return 操作结果
     */
    @DeleteMapping("/{courseId}/subscribe")
    public CommonResponse<Boolean> unsubscribe(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId,
            HttpServletRequest request) {
        log.info("取消课程订阅 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 参数校验
            if (courseId == null || studentId == null) {
                log.error("取消课程订阅失败 - 参数为空, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数不能为空");
            }
            
            // 检查课程是否存在
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                log.warn("取消课程订阅失败 - 课程不存在, 课程ID: {}", courseId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课程不存在");
            }
            
            // 检查是否已订阅
            QueryWrapper<CourseSubscribe> checkWrapper = new QueryWrapper<>();
            checkWrapper.eq("course_id", courseId).eq("student_id", studentId);
            Long count = courseSubscribeMapper.selectCount(checkWrapper);
            
            if (count == null || count == 0) {
                log.info("取消课程订阅失败 - 未订阅过, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "未订阅过该课程", true);
            }
            
            // 删除订阅记录 - 使用简单的SQL删除
            String sql = "DELETE FROM course_subscribe WHERE course_id = ? AND student_id = ?";
            int deleteResult = jdbcTemplate.update(sql, courseId, studentId);
            
            log.info("SQL删除结果: {}", deleteResult);
            
            if (deleteResult > 0) {
                // 更新课程订阅人数
                try {
                    Integer subscriberCount = course.getSubscriberCount();
                    if (subscriberCount == null || subscriberCount <= 0) {
                        subscriberCount = 1; // 至少有1个，即将被删除的
                    }
                    
                    course.setSubscriberCount(subscriberCount - 1);
                    courseMapper.updateById(course);
                    log.info("更新课程订阅人数成功 - 课程ID: {}, 更新后订阅人数: {}", 
                            courseId, course.getSubscriberCount());
                } catch (Exception e) {
                    log.error("更新课程订阅人数失败 - 课程ID: {}, 错误: {}", courseId, e.getMessage());
                }
                
                // 日志记录
                User user = userService.getById(studentId);
                String username = user != null ? user.getUsername() : null;
                String ip = request.getRemoteAddr();
                String userAgent = request.getHeader("User-Agent");
                String courseTitle = course != null ? course.getTitle() : null;
                logService.recordCourseSubscribe(studentId, username, courseId, courseTitle, ip, userAgent, false);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "取消订阅成功", true);
            } else {
                log.error("删除课程订阅记录失败 - 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "取消订阅失败");
            }
        } catch (Exception e) {
            log.error("取消课程订阅异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage(), e);
            e.printStackTrace();
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "取消订阅异常: " + e.getMessage());
        }
    }

    /**
     * 根据学生ID获取订阅的课程列表
     * @param studentId 学生ID
     * @return 课程列表
     */
    @GetMapping("/subscribed/{studentId}")
    public CommonResponse<List<Course>> getSubscribedCoursesByStudent(@PathVariable Integer studentId) {
        log.info("获取学生订阅课程列表 - 学生ID: {}", studentId);
        try {
            QueryWrapper<CourseSubscribe> wrapper = new QueryWrapper<>();
            wrapper.eq("student_id", studentId);
            List<CourseSubscribe> subscribes = courseSubscribeMapper.selectList(wrapper);

            if (subscribes == null || subscribes.isEmpty()) {
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "暂无订阅课程", new java.util.ArrayList<>());
            }

            java.util.List<Integer> courseIds = subscribes.stream()
                    .map(CourseSubscribe::getCourseId)
                    .distinct()
                    .collect(java.util.stream.Collectors.toList());
            List<Course> courses = courseMapper.selectBatchIds(courseIds);
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "获取成功", courses);
        } catch (Exception e) {
            log.error("获取订阅课程异常 - 学生ID: {}, 错误: {}", studentId, e.getMessage(), e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "获取订阅课程异常");
        }
    }
}